package com.swak.utils;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 信号处理
 * 
 * @author 618lf
 */
public class Signals {

	private static final Logger LOG = LoggerFactory.getLogger(Signals.class);

	private static final SignalAccessor SIGNAL_ACCESSOR = getSignalAccessor0();

	public static final String SIG_USR2 = "USR2";

	public static boolean supportSignal() {
		return SIGNAL_ACCESSOR != null;
	}

	/**
	 * Registers user signal handlers.
	 *
	 * @param signalName a signal name
	 * @param handlers   user signal handlers
	 * @return true if support on current platform
	 */
	public static boolean addSignal(final String signalName, final List<SignalHandler> handlers) {
		if (SIGNAL_ACCESSOR != null) {
			SIGNAL_ACCESSOR.addSignal(signalName, handlers);
			return true;
		}
		return false;
	}

	private static SignalAccessor getSignalAccessor0() {
		return hasSignal0() ? new SignalAccessor() : null;
	}

	private static boolean hasSignal0() {
		try {
			Class.forName("sun.misc.Signal");
			return true;
		} catch (final Throwable t) {
			if (LOG.isWarnEnabled()) {
				LOG.warn("sun.misc.Signal: unavailable.", t);
			}
		}
		return false;
	}

	private Signals() {
	}

	@FunctionalInterface
	static interface SignalHandler {
		void handle(String name);
	}

	static class SignalAccessor {

		public void addSignal(final String signalName, final List<SignalHandler> handlers) {
			final sun.misc.Signal signal = new sun.misc.Signal(signalName);
			final SignalHandlerAdapter adapter = new SignalHandlerAdapter(signal, handlers);
			sun.misc.Signal.handle(signal, adapter);
		}
	}

	static class SignalHandlerAdapter implements sun.misc.SignalHandler {

		private final sun.misc.Signal target;
		private final List<SignalHandler> handlers;

		public static void addSignal(final SignalHandlerAdapter adapter) {
			sun.misc.Signal.handle(adapter.target, adapter);
		}

		public SignalHandlerAdapter(sun.misc.Signal target, List<SignalHandler> handlers) {
			this.target = target;
			this.handlers = handlers;
		}

		@Override
		public void handle(final sun.misc.Signal signal) {
			try {
				if (!this.target.equals(signal)) {
					return;
				}

				LOG.info("Handling signal {}.", signal);

				for (final SignalHandler h : this.handlers) {
					h.handle(signal.getName());
				}
			} catch (final Throwable t) {
				LOG.error("Fail to handle signal: {}.", signal, t);
			}
		}
	}
}
